<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="form.dp_id ? '编辑' : '添加'" v-model="visible" align-center
    width="800px" :z-index="2000" @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top" :label-width="140" class="grid grid-cols-2 gap-x-3">
      <el-form-item label="备库需求单号" prop="demand_no" :rules="[{ required: false, message: '不能为空', trigger: 'change' }]">
        <el-input v-model="form.demand_no" placeholder="备库需求单号" class="w-full" @change="handleChange" />
      </el-form-item>
      <el-form-item label="需求ID" prop="sku_no" :rules="[{ required: false, message: '不能为空', trigger: 'change' }]">
        <el-input v-model="form.sku_no" placeholder="备库需求单号" class="w-full" @change="handleChange" />
      </el-form-item>
      <el-form-item label="sku" prop="sku" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
        <el-input v-model="form.sku" placeholder="sku" class="w-full" @change="handleChange" />
      </el-form-item>
      <el-form-item label="采购单号" prop="purchase_no" :rules="[{ required: false, message: '不能为空', trigger: 'change' }]">
        <el-input v-model="form.purchase_no" placeholder="请输入" class="w-full" />
      </el-form-item>
      <el-form-item label="发货仓" prop="shipping_warehouse"
        :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
        <VSelect v-model="form.shipping_warehouse" placeholder="请选择" :options="options.shipping_warehouse"
          class="w-full" />
      </el-form-item>
      <el-form-item label="发货计划类型" prop="plan_type"
        :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
        <VSelect v-model="form.plan_type" placeholder="请选择" :options="options.plan_type"
          class="w-full" />
      </el-form-item>
      <el-form-item label="部门" prop="department_id" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
        <VCascader v-model="form.department_id" placeholder="请输入" type="1" filterable clearable checkStrictly
          class="w-full" />
        </el-form-item>
        <el-form-item label="ASIN" prop="asin">
          <el-input v-model="form.asin" placeholder="ASIN" class="w-full" />
        </el-form-item>
        <el-form-item label="国家" prop="country" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.country" placeholder="请输入" :options="options.country || []" filterable clearable select
          class="w-full" @change="form.delivery_method=null"/>
        </el-form-item>
        <el-form-item label="销售" prop="sale_id" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-if="saleOptions.length" v-model="form.sale_id" placeholder="请选择" :options="saleOptions" class="w-full" />
          <VCascader v-else v-model="form.sale_id" placeholder="请输入" filterable clearable checkStrictly
            class="w-full" />
      </el-form-item>
      <el-form-item label="平台">
        <VSelect v-model="form.platform" placeholder="请输入" :options="options.platform || []" filterable clearable
          class="w-full" />
      </el-form-item>
      <el-form-item label="实际运输方式" prop="transport_type"
        :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
        <VSelect v-model="form.transport_type" placeholder="请输入" :options="options.transport_type || []" filterable
          select clearable class="w-full" @change="form.delivery_method=null"/>
      </el-form-item>

      <el-form-item label="派送方式" prop="delivery_method">
        <VSelect v-model="form.delivery_method" placeholder="请输入" :options="matchedDeliveryList || []" filterable
          select clearable class="w-full" />
      </el-form-item>

      <el-form-item label="预计发货数量" prop="deliver_num" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
        <el-input-number v-model="form.deliver_num" controls-position="right" :min="0" :step="1" :precision="0"
          class="w-full" />
      </el-form-item>
      <el-form-item label="预计发货日期" prop="deliver_time"
        :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
        <el-date-picker v-model="form.deliver_time" placeholder="日期选择" type="date" value-format="YYYY-MM-DD"
          class="w-full" />
      </el-form-item>
      <el-form-item label="目的仓" prop="deliver_time">
        <VSelect v-model="form.destination_warehouse" placeholder="请选择" :options="options.destination_warehouse" select
          class="w-full" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings['create' + 1]" @click="create(1)">确 定</el-button>
      <el-button v-if="form.dp_id" type="primary" :loading="loadings['create' + 2]" @click="create(2)">提 交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage, ElMessageBox } from 'element-plus'
const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const {options} = toRefs(props)
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})

// 表单处理
const formRef = ref()
const form = ref({})
const saleOptions = ref([])

const handleChange = () => {
  const { demand_no, sku, sku_no } = form.value
  if (demand_no && sku && sku_no) {
    api.relation({ demand_no, sku, sku_no }).then(res => {
      const { sale_id, plan_type } = res.data
      saleOptions.value = sale_id
      form.value = Object.assign({}, form.value, res.data, { sale_id: 0 })
    }).catch(() => {
      saleOptions.value = []
      form.value.sale_id = null
    })
  } else {
    form.value.sale_id = null
    saleOptions.value = []
  }
}

// 打开弹窗
const open = async (id) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  loadings = reactive({})
  visible.value = true
  if (id) {
    loadings.detail = true
    const res = await api.deliverPlanDetail({ dp_id: id })
    loadings.detail = false
    form.value = res.data
    const { demand_no, sku, sku_no } = form.value
    if (demand_no && sku && sku_no) {
      api.getSale({ demand_no, sku, sku_no }).then(res => {
        saleOptions.value = res?.data || []
      })
    }
  } else {
    //新增
    form.value = {
      purchase_no: '',
      is_skip: 1
    }
  }
  loadings = reactive({})
  visible.value = true
  formRef?.value?.resetFields()
}

const matchedDeliveryList = computed(() => {
  const { transport_type, country } = form.value;
  const { processDeliveryMethod = [] } = options.value;
  if (!transport_type && !country) {
    return processDeliveryMethod.flatMap(item => 
      item.delivery_method.map(m => ({ label: m.name, value: m.id }))
    );
  }
  const matchedItem = transport_type
    ? processDeliveryMethod.find(d => d.id === transport_type)
    : null;
  if (transport_type && !matchedItem) return [];
  const deliveryMethods = matchedItem ? matchedItem.delivery_method : 
    processDeliveryMethod.flatMap(item => item.delivery_method);
  return deliveryMethods
    .filter(m => !country || m.country.includes(country))
    .map(m => ({ label: m.name, value: m.id }));
});

// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const create = async (type) => {
  if (!await formRef?.value.validate()) return
  loadings['create' + type] = true
  const { dp_id } = form.value
  api[dp_id ? 'edit' : 'create'](form.value).then(async res => {
    const { code, data, message } = res
    const { is_skip } = data
    if (code === 200) {
      if (type === 2) {
        await api.submit({ dp_id })
        ElMessage.success('保存成功')
        emit('success')
      } else {
        ElMessage.success('保存成功')
        emit('success')
      }
      close()
      return
    }
    if (is_skip === 2) {
      ElMessageBox.confirm(message, '提示', {
        type: 'error', confirmButtonText: '是',
        cancelButtonText: '否'
      }).then(res => {
        form.value.is_skip = 2
        create()
      }).finally(() => {
        loadings['create' + type] = false
      })
    } else {
      ElMessage.error(message)
    }
  }).finally(() => {
    loadings['create' + type] = false
  })
}

defineExpose({ open })
</script>